package com.irishud.hudnavi;

import android.net.Credentials;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

import de.greenrobot.event.EventBus;

public class CanServerRunnable {
	private static final String TAG = "CAN ServerRunnable";
	private static final String SOCKET_NAME = "com.dsit.can";
	Thread acceptThrad;

	public CanServerRunnable(){
		acceptThrad = new Thread(new Runnable() {
			@Override
			public void run() {
				LocalServerSocket srv = null;
				try {
					srv = new LocalServerSocket(SOCKET_NAME);
					while (true){
						Log.e(TAG, "wait for socket client connection --------<");
						LocalSocket client = srv.accept();
						Log.e(TAG, "new client connected! ");
						Credentials cre = client.getPeerCredentials();
						Log.i(TAG, "accept socket uid:" + cre.getUid());
						handleClient(client);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		acceptThrad.start();
	}

	void handleClient(LocalSocket client){
		ClientThread th = new ClientThread(client);
		th.start();
	}

	class ClientThread extends Thread {
		LocalSocket connect;
		public ClientThread(LocalSocket client){
			connect = client;
		}
		@Override
		public void run() {
			boolean isRunning = true;
			InputStream in;
			int len;
			try {
				while (isRunning && !interrupted()) {
					in = connect.getInputStream();
					byte[] buffer = new byte[512];
					len=in.read(buffer,0,512);
					if(len == -1)
						continue;
					String strece = "";
					for (int i = 0; i < len;i++) {
						byte a = buffer[i];
						int inta = a;
						inta = inta & 0xff;
						strece = strece + inta + ".";
					}
					Log.d(TAG, "can data" + " len:" + len + " str:" + strece);
//				Log.i(TAG,"CAN bus data read bytes:"+len);
					EventBus.getDefault().post(new CanBusEvent(len,buffer));
					Log.i(TAG, "eventbus send ------> ok");
				}
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(TAG, "Error canbus " + e.getMessage());
			} finally{
				Log.e(TAG, "finally error");
				isRunning = false;
				try {
					connect.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				interrupted();// self-killed
			}
		}
	}
}